{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Topic Modeling with NMF and SVD"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## The problem"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Topic modeling is a fun way to start our study of NLP. We will use two popular **matrix decomposition techniques**. \n",
    "\n",
    "We start with a **term-document matrix**:\n",
    "\n",
    "<img src=\"images/document_term.png\" alt=\"term-document matrix\" style=\"width: 80%\"/>\n",
    "\n",
    "source: [Introduction to Information Retrieval](http://player.slideplayer.com/15/4528582/#)\n",
    "\n",
    "We can decompose this into one tall thin matrix times one wide short matrix (possibly with a diagonal matrix in between).\n",
    "\n",
    "Notice that this representation does not take into account word order or sentence structure.  It's an example of a **bag of words** approach."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Latent Semantic Analysis (LSA) uses Singular Value Decomposition (SVD)."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Motivation"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Consider the most extreme case - reconstructing the matrix using an outer product of two vectors. Clearly, in most cases we won't be able to reconstruct the matrix exactly. But if we had one vector with the relative frequency of each vocabulary word out of the total word count, and one with the average number of words per document, then that outer product would be as close as we can get.\n",
    "\n",
    "Now consider increasing that matrices to two columns and two rows. The optimal decomposition would now be to cluster the documents into two groups, each of which has as different a distribution of words as possible to each other, but as similar as possible amongst the documents in the cluster. We will call those two groups \"topics\". And we would cluster the words into two groups, based on those which most frequently appear in each of the topics. "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Getting started"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We'll take a dataset of documents in several different categories, and find topics (consisting of groups of words) for them.  Knowing the actual categories helps us evaluate if the topics we find make sense.\n",
    "\n",
    "We will try this with two different matrix factorizations: **Singular Value Decomposition (SVD)** and **Non-negative Matrix Factorization (NMF)**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 138,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "from sklearn.datasets import fetch_20newsgroups\n",
    "from sklearn import decomposition\n",
    "from scipy import linalg\n",
    "import matplotlib.pyplot as plt"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 139,
   "metadata": {},
   "outputs": [],
   "source": [
    "%matplotlib inline\n",
    "np.set_printoptions(suppress=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Additional Resources"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- [Data source](http://scikit-learn.org/stable/datasets/twenty_newsgroups.html): Newsgroups are discussion groups on Usenet, which was popular in the 80s and 90s before the web really took off.  This dataset includes 18,000 newsgroups posts with 20 topics.\n",
    "- [Chris Manning's book chapter](https://nlp.stanford.edu/IR-book/pdf/18lsi.pdf) on matrix factorization and LSI \n",
    "- Scikit learn [truncated SVD LSI details](http://scikit-learn.org/stable/modules/decomposition.html#lsa)\n",
    "\n",
    "### Other Tutorials\n",
    "- [Scikit-Learn: Out-of-core classification of text documents](http://scikit-learn.org/stable/auto_examples/applications/plot_out_of_core_classification.html): uses [Reuters-21578](https://archive.ics.uci.edu/ml/datasets/reuters-21578+text+categorization+collection) dataset (Reuters articles labeled with ~100 categories), HashingVectorizer\n",
    "- [Text Analysis with Topic Models for the Humanities and Social Sciences](https://de.dariah.eu/tatom/index.html): uses [British and French Literature dataset](https://de.dariah.eu/tatom/datasets.html) of Jane Austen, Charlotte Bronte, Victor Hugo, and more"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Look at our data"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Scikit Learn comes with a number of built-in datasets, as well as loading utilities to load several standard external datasets. This is a [great resource](http://scikit-learn.org/stable/datasets/), and the datasets include Boston housing prices, face images, patches of forest, diabetes, breast cancer, and more.  We will be using the newsgroups dataset.\n",
    "\n",
    "Newsgroups are discussion groups on Usenet, which was popular in the 80s and 90s before the web really took off.  This dataset includes 18,000 newsgroups posts with 20 topics.  "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 140,
   "metadata": {},
   "outputs": [],
   "source": [
    "categories = ['alt.atheism', 'talk.religion.misc', 'comp.graphics', 'sci.space']\n",
    "remove = ('headers', 'footers', 'quotes')\n",
    "newsgroups_train = fetch_20newsgroups(subset='train', categories=categories, remove=remove)\n",
    "newsgroups_test = fetch_20newsgroups(subset='test', categories=categories, remove=remove)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 141,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "((2034,), (2034,))"
      ]
     },
     "execution_count": 141,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "newsgroups_train.filenames.shape, newsgroups_train.target.shape"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's look at some of the data.  Can you guess which category these messages are in?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Hi,\n",
      "\n",
      "I've noticed that if you only save a model (with all your mapping planes\n",
      "positioned carefully) to a .3DS file that when you reload it after restarting\n",
      "3DS, they are given a default position and orientation.  But if you save\n",
      "to a .PRJ file their positions/orientation are preserved.  Does anyone\n",
      "know why this information is not stored in the .3DS file?  Nothing is\n",
      "explicitly said in the manual about saving texture rules in the .PRJ file. \n",
      "I'd like to be able to read the texture rule information, does anyone have \n",
      "the format for the .PRJ file?\n",
      "\n",
      "Is the .CEL file format available from somewhere?\n",
      "\n",
      "Rych\n",
      "\n",
      "\n",
      "Seems to be, barring evidence to the contrary, that Koresh was simply\n",
      "another deranged fanatic who thought it neccessary to take a whole bunch of\n",
      "folks with him, children and all, to satisfy his delusional mania. Jim\n",
      "Jones, circa 1993.\n",
      "\n",
      "\n",
      "Nope - fruitcakes like Koresh have been demonstrating such evil corruption\n",
      "for centuries.\n",
      "\n",
      " >In article <1993Apr19.020359.26996@sq.sq.com>, msb@sq.sq.com (Mark Brader) \n",
      "\n",
      "MB>                                                             So the\n",
      "MB> 1970 figure seems unlikely to actually be anything but a perijove.\n",
      "\n",
      "JG>Sorry, _perijoves_...I'm not used to talking this language.\n",
      "\n",
      "Couldn't we just say periapsis or apoapsis?\n",
      "\n",
      " \n"
     ]
    }
   ],
   "source": [
    "print(\"\\n\".join(newsgroups_train.data[:3]))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "hint: definition of *perijove* is the point in the orbit of a satellite of Jupiter nearest the planet's center "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array(['comp.graphics', 'talk.religion.misc', 'sci.space'], dtype='<U18')"
      ]
     },
     "execution_count": 27,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "np.array(newsgroups_train.target_names)[newsgroups_train.target[:3]]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The target attribute is the integer index of the category."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([1, 3, 2, 0, 2, 0, 2, 1, 2, 1])"
      ]
     },
     "execution_count": 28,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "newsgroups_train.target[:10]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {},
   "outputs": [],
   "source": [
    "num_topics, num_top_words = 6, 8"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Stop words, stemming, lemmatization"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Stop words"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "From [Intro to Information Retrieval](https://nlp.stanford.edu/IR-book/html/htmledition/dropping-common-terms-stop-words-1.html):\n",
    "\n",
    "*Some extremely common words which would appear to be of little value in helping select documents matching a user need are excluded from the vocabulary entirely. These words are called stop words.*\n",
    "\n",
    "*The general trend in IR systems over time has been from standard use of quite large stop lists (200-300 terms) to very small stop lists (7-12 terms) to no stop list whatsoever. Web search engines generally do not use stop lists.*"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### NLTK"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['a',\n",
       " 'about',\n",
       " 'above',\n",
       " 'across',\n",
       " 'after',\n",
       " 'afterwards',\n",
       " 'again',\n",
       " 'against',\n",
       " 'all',\n",
       " 'almost',\n",
       " 'alone',\n",
       " 'along',\n",
       " 'already',\n",
       " 'also',\n",
       " 'although',\n",
       " 'always',\n",
       " 'am',\n",
       " 'among',\n",
       " 'amongst',\n",
       " 'amoungst']"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from sklearn.feature_extraction import stop_words\n",
    "\n",
    "sorted(list(stop_words.ENGLISH_STOP_WORDS))[:20]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "There is no single universal list of stop words."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Stemming and Lemmatization"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "from [Information Retrieval](https://nlp.stanford.edu/IR-book/html/htmledition/stemming-and-lemmatization-1.html) textbook:\n",
    "\n",
    "Are the below words the same?\n",
    "\n",
    "*organize, organizes, and organizing*\n",
    "\n",
    "*democracy, democratic, and democratization*"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Stemming and Lemmatization both generate the root form of the words. \n",
    "\n",
    "Lemmatization uses the rules about a language.  The resulting tokens are all actual words\n",
    "\n",
    "\"Stemming is the poor-man’s lemmatization.\" (Noah Smith, 2011) Stemming is a crude heuristic that chops the ends off of words.  The resulting tokens may not be actual words. Stemming is faster."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 142,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "[nltk_data] Downloading package wordnet to\n",
      "[nltk_data]     /home/racheltho/nltk_data...\n",
      "[nltk_data]   Package wordnet is already up-to-date!\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 142,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import nltk\n",
    "nltk.download('wordnet')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 143,
   "metadata": {},
   "outputs": [],
   "source": [
    "from nltk import stem"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 144,
   "metadata": {},
   "outputs": [],
   "source": [
    "wnl = stem.WordNetLemmatizer()\n",
    "porter = stem.porter.PorterStemmer()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 145,
   "metadata": {},
   "outputs": [],
   "source": [
    "word_list = ['feet', 'foot', 'foots', 'footing']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 146,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['foot', 'foot', 'foot', 'footing']"
      ]
     },
     "execution_count": 146,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "[wnl.lemmatize(word) for word in word_list]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 147,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['feet', 'foot', 'foot', 'foot']"
      ]
     },
     "execution_count": 147,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "[porter.stem(word) for word in word_list]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Your turn!  Now, try lemmatizing and stemming the following collections of words:\n",
    "\n",
    "- fly, flies, flying\n",
    "- organize, organizes, organizing\n",
    "- universe, university"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "fastai/course-nlp"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Stemming and lemmatization are language dependent.  Languages with more complex morphologies may show bigger benefits.  For example, Sanskrit has a very [large number of verb forms](https://en.wikipedia.org/wiki/Sanskrit_verbs). "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Spacy"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Stemming and lemmatization are implementation dependent."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Spacy is a very modern & fast nlp library. Spacy is opinionated, in that it typically offers one highly optimized way to do something (whereas nltk offers a huge variety of ways, although they are usually not as optimized).\n",
    "\n",
    "You will need to install it.\n",
    "\n",
    "if you use conda:\n",
    "```\n",
    "conda install -c conda-forge spacy\n",
    "```\n",
    "if you use pip:\n",
    "```\n",
    "pip install -U spacy\n",
    "```\n",
    "\n",
    "You will then need to download the English model:\n",
    "```\n",
    "spacy -m download en_core_web_sm\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "import spacy"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 80,
   "metadata": {},
   "outputs": [],
   "source": [
    "from spacy.lemmatizer import Lemmatizer\n",
    "lemmatizer = Lemmatizer()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 81,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['feet', 'foot', 'foots', 'footing']"
      ]
     },
     "execution_count": 81,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "[lemmatizer.lookup(word) for word in word_list]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Spacy doesn't offer a stemmer (since lemmatization is considered better-- this is an example of being opinionated!)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Stop words vary from library to library"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [],
   "source": [
    "nlp = spacy.load(\"en_core_web_sm\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['a',\n",
       " 'about',\n",
       " 'above',\n",
       " 'across',\n",
       " 'after',\n",
       " 'afterwards',\n",
       " 'again',\n",
       " 'against',\n",
       " 'all',\n",
       " 'almost',\n",
       " 'alone',\n",
       " 'along',\n",
       " 'already',\n",
       " 'also',\n",
       " 'although',\n",
       " 'always',\n",
       " 'am',\n",
       " 'among',\n",
       " 'amongst',\n",
       " 'amount']"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "sorted(list(nlp.Defaults.stop_words))[:20]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Exercise: What stop words appear in spacy but not in sklearn?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'ca',\n",
       " 'did',\n",
       " 'does',\n",
       " 'doing',\n",
       " 'just',\n",
       " 'make',\n",
       " 'quite',\n",
       " 'really',\n",
       " 'regarding',\n",
       " 'say',\n",
       " 'unless',\n",
       " 'used',\n",
       " 'using',\n",
       " 'various'}"
      ]
     },
     "execution_count": 27,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#Exercise:\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "heading_collapsed": true
   },
   "source": [
    "#### Exercise: And what stop words are in sklearn but not spacy?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {
    "hidden": true
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "frozenset({'amoungst',\n",
       "           'bill',\n",
       "           'cant',\n",
       "           'co',\n",
       "           'con',\n",
       "           'couldnt',\n",
       "           'cry',\n",
       "           'de',\n",
       "           'describe',\n",
       "           'detail',\n",
       "           'eg',\n",
       "           'etc',\n",
       "           'fill',\n",
       "           'find',\n",
       "           'fire',\n",
       "           'found',\n",
       "           'hasnt',\n",
       "           'ie',\n",
       "           'inc',\n",
       "           'interest',\n",
       "           'ltd',\n",
       "           'mill',\n",
       "           'sincere',\n",
       "           'system',\n",
       "           'thick',\n",
       "           'thin',\n",
       "           'un'})"
      ]
     },
     "execution_count": 28,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#Exercise:\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "heading_collapsed": true
   },
   "source": [
    "### When to use these?"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "hidden": true
   },
   "source": [
    "<img src=\"images/skomoroch.png\" alt=\"\" style=\"width: 65%\"/>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "hidden": true
   },
   "source": [
    "These were long considered standard techniques, but they can often **hurt** your performance **if using deep learning**. Stemming, lemmatization, and removing stop words all involve throwing away information.\n",
    "\n",
    "However, they can still be useful when working with simpler models."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "heading_collapsed": true
   },
   "source": [
    "### Another approach: sub-word units"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "hidden": true
   },
   "source": [
    "[SentencePiece](https://github.com/google/sentencepiece) library from Google"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Data Processing"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Next, scikit learn has a method that will extract all the word counts for us.  In the next lesson, we'll learn how to write our own version of CountVectorizer, to see what's happening underneath the hood."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 148,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 149,
   "metadata": {},
   "outputs": [],
   "source": [
    "import nltk\n",
    "# nltk.download('punkt')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 133,
   "metadata": {},
   "outputs": [],
   "source": [
    "# from nltk import word_tokenize\n",
    "\n",
    "# class LemmaTokenizer(object):\n",
    "#     def __init__(self):\n",
    "#         self.wnl = stem.WordNetLemmatizer()\n",
    "#     def __call__(self, doc):\n",
    "#         return [self.wnl.lemmatize(t) for t in word_tokenize(doc)]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 150,
   "metadata": {},
   "outputs": [],
   "source": [
    "vectorizer = CountVectorizer(stop_words='english') #, tokenizer=LemmaTokenizer())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 151,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(2034, 26576)"
      ]
     },
     "execution_count": 151,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "vectors = vectorizer.fit_transform(newsgroups_train.data).todense() # (documents, vocab)\n",
    "vectors.shape #, vectors.nnz / vectors.shape[0], row_means.shape"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 108,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2034 (2034, 26576)\n"
     ]
    }
   ],
   "source": [
    "print(len(newsgroups_train.data), vectors.shape)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 109,
   "metadata": {},
   "outputs": [],
   "source": [
    "vocab = np.array(vectorizer.get_feature_names())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 110,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(26576,)"
      ]
     },
     "execution_count": 110,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "vocab.shape"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 111,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array(['cosmonauts', 'cosmos', 'cosponsored', 'cost', 'costa', 'costar',\n",
       "       'costing', 'costly', 'costruction', 'costs', 'cosy', 'cote',\n",
       "       'couched', 'couldn', 'council', 'councils', 'counsel',\n",
       "       'counselees', 'counselor', 'count'], dtype='<U80')"
      ]
     },
     "execution_count": 111,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "vocab[7000:7020]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Singular Value Decomposition (SVD)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\"SVD is not nearly as famous as it should be.\" - Gilbert Strang"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We would clearly expect that the words that appear most frequently in one topic would appear less frequently in the other - otherwise that word wouldn't make a good choice to separate out the two topics. Therefore, we expect the topics to be **orthogonal**.\n",
    "\n",
    "The SVD algorithm factorizes a matrix into one matrix with **orthogonal columns** and one with **orthogonal rows** (along with a diagonal matrix, which contains the **relative importance** of each factor).\n",
    "\n",
    "<img src=\"images/svd_fb.png\" alt=\"\" style=\"width: 80%\"/>\n",
    "(source: [Facebook Research: Fast Randomized SVD](https://research.fb.com/fast-randomized-svd/))\n",
    "\n",
    "SVD is an **exact decomposition**, since the matrices it creates are big enough to fully cover the original matrix. SVD is extremely widely used in linear algebra, and specifically in data science, including:\n",
    "\n",
    "- semantic analysis\n",
    "- collaborative filtering/recommendations ([winning entry for Netflix Prize](https://datajobs.com/data-science-repo/Recommender-Systems-%5BNetflix%5D.pdf))\n",
    "- calculate Moore-Penrose pseudoinverse\n",
    "- data compression\n",
    "- principal component analysis"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Latent Semantic Analysis (LSA) uses SVD.  You will sometimes hear topic modelling referred to as LSA."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 152,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 1min 19s, sys: 10 s, total: 1min 29s\n",
      "Wall time: 3.63 s\n"
     ]
    }
   ],
   "source": [
    "%time U, s, Vh = linalg.svd(vectors, full_matrices=False)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 153,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(2034, 2034) (2034,) (2034, 26576)\n"
     ]
    }
   ],
   "source": [
    "print(U.shape, s.shape, Vh.shape)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Confirm this is a decomposition of the input."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 157,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([433.92698542, 291.51012741, 240.71137677, 220.00048043])"
      ]
     },
     "execution_count": 157,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "s[:4]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 158,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([433.92698542, 291.51012741, 240.71137677, 220.00048043])"
      ]
     },
     "execution_count": 158,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "np.diag(np.diag(s[:4]))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Answer"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 132,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 132,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#Exercise: confrim that U, s, Vh is a decomposition of `vectors`\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Confirm that U, V are orthonormal"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "heading_collapsed": true
   },
   "source": [
    "#### Answer"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "metadata": {
    "hidden": true
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 39,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#Exercise: Confirm that U, Vh are orthonormal\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "heading_collapsed": true
   },
   "source": [
    "#### Topics"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "hidden": true
   },
   "source": [
    "What can we say about the singular values s?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 114,
   "metadata": {
    "hidden": true
   },
   "outputs": [
    {
     "data": {
      "image/png": "iVBORw0KGgoAAAANSUhEUgAAAXoAAAD8CAYAAAB5Pm/hAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAADl0RVh0U29mdHdhcmUAbWF0cGxvdGxpYiB2ZXJzaW9uIDMuMC4yLCBodHRwOi8vbWF0cGxvdGxpYi5vcmcvOIA7rQAAGXBJREFUeJzt3X2MHPd93/H3d2bvibzj85GiSdqUbNqWEMSSTDtMHBuNlSqynJjKgwqlacW6qoUgdmvDKRKlRtMUKFCrD3YqJFCqRoIpQ4nt2DFEGHJsQZaqFLAlkXqWKIuULIln0uSJz+Q97u63f8xv75Z3Ozt7x9uHWX1ewGJmfzO7++Xs8TO//e3sjLk7IiLSvaJ2FyAiIs2loBcR6XIKehGRLqegFxHpcgp6EZEup6AXEelyCnoRkS6noBcR6XIKehGRLldodwEA69at861bt7a7DBGRXNm3b9+b7j6ctV5HBP3WrVvZu3dvu8sQEckVM3u9kfU0dCMi0uUU9CIiXU5BLyLS5RT0IiJdTkEvItLlFPQiIl1OQS8i0uVyHfRPvHaCL33/x0wVy+0uRUSkY+U66Pe9fpI7fnCQYllBLyKSJtdBb2Gq65uLiKTLd9CHpFfOi4iky3fQz/TpRUQkTa6DvsI1diMikirXQa+hGxGRbLkO+gp16EVE0uU66E1dehGRTPkO+jB1Jb2ISKp8B32lQ6+cFxFJle+gD1PlvIhIunwHvek4ehGRLA0HvZnFZvaUmX0n3L/UzB4zswNm9nUz6w3tfeH+wbB8a3NKn6Xj6E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jZUmSf5Uu/58PqVb/F3AfdX1XVzOBJgB3C68nGzCS7ocbV7W1VZ6Lb5HnCtma0OwxfXhrYlY2bXAX8MfMLdx6rah80sDvOXkWybV0NdZ81sR/jbvLnq37FUNS30/Wrl/89fBV5y95khmVZtq7QsoNP+rpbqW9123Ei+wX6ZZG/9hRa+7i+TfKx6Fng63K4Hvgo8F9r3ABurHvOFUOePuYhv+TPquozk6IZngBcq2wRYCzwEHAjTNaHdgL8MdT0HbG9SXcuA48DKqraWbyuSHc0RYJqkB3XLYrYNybj5wXD7ZBNqOkgyXlv52/qrsO5vh/f1GeBJ4Deqnmc7Sfi+AvwF4ceQS1jTgt+vpf7/Wauu0P4V4PfnrNuqbZWWBW39u5p70y9jRUS6XJ6HbkREpAEKehGRLqegFxHpcgp6EZEup6AXEelyCnoRkS6noBcR6XIKehGRLvf/AV2RYlNTShJWAAAAAElFTkSuQmCC\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "plt.plot(s);"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 102,
   "metadata": {
    "hidden": true
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[<matplotlib.lines.Line2D at 0x7f1781c7aa58>]"
      ]
     },
     "execution_count": 102,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "data": {
      "image/png": "iVBORw0KGgoAAAANSUhEUgAAAYAAAAD8CAYAAAB+UHOxAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAADl0RVh0U29mdHdhcmUAbWF0cGxvdGxpYiB2ZXJzaW9uIDMuMC4yLCBodHRwOi8vbWF0cGxvdGxpYi5vcmcvOIA7rQAAHwdJREFUeJzt3X2UXHWd5/H3tx76Mf1QlXRC6CRdAcJDQEnoSojguo4ooM4aR8dZOI4yLiO6E1yc45kd9MwenXE5x52jMjoiKwiKjoIcxCXjcmRA8cw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iisS3gF+5+4XApUT4ezGzZuC/AVl3vwSIA9eFW9X0KrsAAJYDW9x9q7v3Aw8AK0OuKTTuvtvdnw+2D5D/D94cblXhMbN5wAeB74ddS9jMrB54F3APgLv3u3t3uFWFLgFUm1kCqAF2hVzPtCrHAGgGdhTcbyfCv/AKmVkGWAo8G24lofon4L8Dp3cV7/JwDtAB/CAYEvu+mU3NRXJLkLvvBL4ObAd2A/vc/d/CrWp6lWMA2BhtkT/UycxmAD8HPu/u+8OuJwxm9sfAHndfG3YtRSIBXAbc6e5LgUNAZOfMzCxFfrRgIXA2UGtmfx5uVdOrHAOgHZhfcH8eZb4bNx4zS5L/5f8Td3847HpCdCXwITNrIz80+B4z+5dwSwpVO9Du7iN7hA+RD4Soei/wurt3uPsA8DBwRcg1TatyDIA1wCIzW2hmFeQncVaHXFNozMzIj/Fucvdvhl1PmNz9i+4+z90z5P9d/Mbdy/ovvJNx9zeAHWZ2QdB0FfByiCWFbTuwwsxqgv83V1Hmk+KJsAuYau4+aGY3A4+Rn8W/1903hlxWmK4EPgG8ZGYvBG1fcvdHQ6xJisfngJ8EfyxtBT4Vcj2hcfdnzewh4HnyR8+to8zPCtaZwCIiEVWOQ0AiIjIBCgARkYhSAIiIRJQCQEQkohQAIiIRpQAQEYkoBYCISEQpAEREIur/A8bAc5ovxt0fAAAAAElFTkSuQmCC\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "plt.plot(s[:10])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 104,
   "metadata": {
    "hidden": true
   },
   "outputs": [],
   "source": [
    "num_top_words=8\n",
    "\n",
    "def show_topics(a):\n",
    "    top_words = lambda t: [vocab[i] for i in np.argsort(t)[:-num_top_words-1:-1]]\n",
    "    topic_words = ([top_words(t) for t in a])\n",
    "    return [' '.join(t) for t in topic_words]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 115,
   "metadata": {
    "hidden": true
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['critus ditto propagandist surname galacticentric kindergarten surreal imaginative',\n",
       " 'jpeg gif file color quality image jfif format',\n",
       " 'graphics edu pub mail 128 3d ray ftp',\n",
       " 'jesus god matthew people atheists atheism does graphics',\n",
       " 'image data processing analysis software available tools display',\n",
       " 'god atheists atheism religious believe religion argument true',\n",
       " 'space nasa lunar mars probe moon missions probes',\n",
       " 'image probe surface lunar mars probes moon orbit',\n",
       " 'argument fallacy conclusion example true ad argumentum premises',\n",
       " 'space larson image theory universe physical nasa material']"
      ]
     },
     "execution_count": 115,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "show_topics(Vh[:10])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "hidden": true
   },
   "source": [
    "We get topics that match the kinds of clusters we would expect! This is despite the fact that this is an **unsupervised algorithm** - which is to say, we never actually told the algorithm how our documents are grouped."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "hidden": true
   },
   "source": [
    "We will return to SVD in **much more detail** later.  For now, the important takeaway is that we have a tool that allows us to exactly factor a matrix into orthogonal columns and orthogonal rows."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Non-negative Matrix Factorization (NMF)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Motivation"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<img src=\"images/face_pca.png\" alt=\"PCA on faces\" style=\"width: 80%\"/>\n",
    "\n",
    "(source: [NMF Tutorial](http://perso.telecom-paristech.fr/~essid/teach/NMF_tutorial_ICME-2014.pdf))\n",
    "\n",
    "A more interpretable approach:\n",
    "\n",
    "<img src=\"images/face_outputs.png\" alt=\"NMF on Faces\" style=\"width: 80%\"/>\n",
    "\n",
    "(source: [NMF Tutorial](http://perso.telecom-paristech.fr/~essid/teach/NMF_tutorial_ICME-2014.pdf))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Idea"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Rather than constraining our factors to be *orthogonal*, another idea would to constrain them to be *non-negative*. NMF is a factorization of a non-negative data set $V$: $$ V = W H$$ into non-negative matrices $W,\\; H$. Often positive factors will be **more easily interpretable** (and this is the reason behind NMF's popularity). \n",
    "\n",
    "<img src=\"images/face_nmf.png\" alt=\"NMF on faces\" style=\"width: 80%\"/>\n",
    "\n",
    "(source: [NMF Tutorial](http://perso.telecom-paristech.fr/~essid/teach/NMF_tutorial_ICME-2014.pdf))\n",
    "\n",
    "Nonnegative matrix factorization (NMF) is a non-exact factorization that factors into one skinny positive matrix and one short positive matrix.  NMF is NP-hard and non-unique.  There are a number of variations on it, created by adding different constraints. "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Applications of NMF"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- [Face Decompositions](http://scikit-learn.org/stable/auto_examples/decomposition/plot_faces_decomposition.html#sphx-glr-auto-examples-decomposition-plot-faces-decomposition-py)\n",
    "- [Collaborative Filtering, eg movie recommendations](http://www.quuxlabs.com/blog/2010/09/matrix-factorization-a-simple-tutorial-and-implementation-in-python/)\n",
    "- [Audio source separation](https://pdfs.semanticscholar.org/cc88/0b24791349df39c5d9b8c352911a0417df34.pdf)\n",
    "- [Chemistry](http://ieeexplore.ieee.org/document/1532909/)\n",
    "- [Bioinformatics](https://bmcbioinformatics.biomedcentral.com/articles/10.1186/s12859-015-0485-4) and [Gene Expression](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC2623306/)\n",
    "- Topic Modeling (our problem!)\n",
    "\n",
    "<img src=\"images/nmf_doc.png\" alt=\"NMF on documents\" style=\"width: 80%\"/>\n",
    "\n",
    "(source: [NMF Tutorial](http://perso.telecom-paristech.fr/~essid/teach/NMF_tutorial_ICME-2014.pdf))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**More Reading**:\n",
    "\n",
    "- [The Why and How of Nonnegative Matrix Factorization](https://arxiv.org/pdf/1401.5226.pdf)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### NMF from sklearn"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We will use [scikit-learn's implementation of NMF](http://scikit-learn.org/stable/modules/generated/sklearn.decomposition.NMF.html):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 116,
   "metadata": {},
   "outputs": [],
   "source": [
    "m,n=vectors.shape\n",
    "d=5  # num topics"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 117,
   "metadata": {},
   "outputs": [],
   "source": [
    "clf = decomposition.NMF(n_components=d, random_state=1)\n",
    "\n",
    "W1 = clf.fit_transform(vectors)\n",
    "H1 = clf.components_"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 118,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['jpeg image gif file color images format quality',\n",
       " 'edu graphics pub mail 128 ray ftp send',\n",
       " 'space launch satellite nasa commercial satellites year market',\n",
       " 'jesus god people matthew atheists does atheism said',\n",
       " 'image data available software processing ftp edu analysis']"
      ]
     },
     "execution_count": 118,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "show_topics(H1)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### TF-IDF"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "[Topic Frequency-Inverse Document Frequency](http://www.tfidf.com/) (TF-IDF) is a way to normalize term counts by taking into account how often they appear in a document, how long the document is, and how commmon/rare the term is.\n",
    "\n",
    "TF = (# occurrences of term t in document) / (# of words in documents)\n",
    "\n",
    "IDF = log(# of documents / # documents with term t in it)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 119,
   "metadata": {},
   "outputs": [],
   "source": [
    "vectorizer_tfidf = TfidfVectorizer(stop_words='english')\n",
    "vectors_tfidf = vectorizer_tfidf.fit_transform(newsgroups_train.data) # (documents, vocab)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 160,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[\"a\\n\\nWhat about positional uncertainties in S-L 1993e?   I assume we know where\\nand what Galileo is doing within a few meters.   But without the\\nHGA,  don't we have to have some pretty good ideas, of where to look\\nbefore imaging?  If the HGA was working,  they could slew around\\nin near real time (Less speed of light delay).  But when they were\\nimaging toutatis????  didn't someone have to get lucky on a guess to\\nfind the first images?   \\n\\nAlso, I imagine S-L 1993e will be mostly a visual image.  so how will\\nthat affect the other imaging missions.  with the LGA,  there is a real\\ntight allocation of bandwidth.   It may be premature to hope for answers,\\nbut I thought i'd throw it on the floor.\",\n",
       " \"I would like to program Tseng ET4000 to nonstandard 1024x768 mode by\\nswitching to standard 1024x768 mode using BIOS and than changing some\\ntiming details (0x3D4 registers 0x00-0x1F) but I don't know how to\\nselect 36 MHz pixel clock I need. The BIOS function selects 40 MHz.\\n\\nIs there anybody who knows where to obtain technical info about this.\\nI am also interested in any other technical information about Tseng ET4000\\nand Trident 8900 and 9000 chipsets.\\n\\n\\t\\t\\tthanks very much\",\n",
       " 'In-Reply-To: <20APR199312262902@rigel.tamu.edu> lmp8913@rigel.tamu.edu (PRESTON, LISA M)',\n",
       " \"\\n\\n\\n\\nI'm not sure, but it almost sounds like they can't figure out where the \\n_nucleus_ is within the coma. If they're off by a couple hundred\\nmiles, well, you can imagine the rest...\\n\",\n",
       " \"Hello,\\n     I am looking to add voice input capability to a user interface I am\\ndeveloping on an HP730 (UNIX) workstation.  I would greatly appreciate \\ninformation anyone would care to offer about voice input systems that are \\neasily accessible from the UNIX environment. \\n\\n     The names or adresses of applicable vendors, as well as any \\nexperiences you have had with specific systems, would be very helpful.\\n\\n     Please respond via email; I will post a summary if there is \\nsufficient interest.\\n\\n\\nThanks,\\nKen\\n\\n\\nP.S.  I have found several impressive systems for IBM PC's, but I would \\nlike to avoid the hassle of purchasing and maintaining a separate PC if \\nat all possible.\\n\\n-------------------------------------------------------------------------------\\nKen Hinckley (kph2q@virginia.edu)\\nUniversity of Virginia \\nNeurosurgical Visualization Laboratory\",\n",
       " '\\nIt was a test of the first reusable tool.\\n\\n\\nPointy so they can find them or so they will stick into their pants better, and\\nbe closer to their brains?',\n",
       " '\\nSize of armies, duration, numbers of casualties both absolute and as a\\npercentage of those involved, geographical area and numbers of countries\\ntoo, are all measures of size.  In this case I\\'d say the relevant\\nstatistic would be the number of combatants (total troops) compared to\\ntotal casualties from among the total civilian population in the\\naffected geographical area.\\n\\n\\nVietnam and Korea might make good comparisons.\\n\\n\\nWestern news in general, but in particular the American \"mass media\":\\nCBS, NBC, ABC, etc.  The general tone of the news during the whole\\nwar was one of \"those poor, poor Iraqis\" along with \"look how precisely\\nthis cruise missile blew this building to bits\".\\n\\n\\nI agree.\\n\\n\\nPerhaps so.  And maybe the atomic bomb was a mistake too.  But that\\'s easy\\nto say from our \"enlightened\" viewpoint here in the 90\\'s, right?  Back\\nthen, it was *all-out* war, and Germany and Japan had to be squashed.\\nAfter all, a million or more British had already died, hundreds of \\nthousands of French, a couple hundread thousand or so Americans, and \\nmillions of Russians, not to mention a few million Jews, Poles, and \\nother people of slavic descent in German concentration camps.  All \\nthings considered, the fire-bombings and the atomic bomb were\\nessential (and therefore justified) in bringing the war to a quick\\nend to avoid even greater allied losses.\\n\\nI, for one, don\\'t regret it.\\n\\n\\nSure.  And it\\'s the people who suffer because of them.  All the more\\nreason to depose these \"entrenched political rulers operating in their\\nown selfish interests\"!  Or do you mean that this applies to the allies\\nas well??\\n\\n\\nI make no claim or effort to justify the misguided foreign policy of the\\nWest before the war.  It is evident that the West, especially America,\\nmisjudged Hussein drastically.  But once Hussein invaded Kuwait and \\nthreatened to militarily corner a significant portion of the world\\'s\\noil supply, he had to be stopped.  Sure the war could have been\\nprevented by judicious and concerted effort on the part of the West\\nbefore Hussein invaded Kuwait, but it is still *Hussein* who is\\nresponsible for his decision to invade.  And once he did so, a\\nstrong response from the West was required.\\n\\n\\nWell, it\\'s not very \"loving\" to allow a Hussein or a Hitler to gobble up\\nnearby countries and keep them.  Or to allow them to continue with mass\\nslaughter of certain peoples under their dominion.  So, I\\'d have to\\nsay yes, stopping Hussein was the most \"loving\" thing to do for the\\nmost people involved once he set his mind on military conquest.\\n\\nI mentioned it.\\n\\nIf we hadn\\'t intervened, allowing Hussein to keep Kuwait, then it would\\nhave been appeasement.  It is precisely the lessons the world learned\\nin WW2 that motivated the Western alliance to war.  Letting Hitler take\\nAustria and Czechoslavkia did not stop WW2 from happening, and letting\\nHussein keep Kuwait would not have stopped an eventual Gulf War to\\nprotect Saudi Arabia.\\n\\n\\nSure.  What was truly unfortunate was that they followed Hitler in\\nhis grandiose quest for a \"Thousand Year Reich\".  The consequences\\nstemmed from that.\\n\\nWhat should I say about them?  Anything in particular?\\n\\n\\n\\nSo?  It was the *policemen* on trial not Rodney King!!  And under American\\nlaw they deserved a jury of *their* peers!  If there had been black\\nofficers involved, I\\'m sure their would have been black jurors too.\\nThis point (of allegedly racial motivations) is really shallow.\\n\\n\\nSo?  It\\'s \"hard to imagine\"?  So when has Argument from Incredulity\\ngained acceptance from the revered author of \"Constructing a Logical\\nArgument\"?  Can we expect another revision soon??  :)  (Just kidding.)\\n\\n\\nI have to admit that I wonder this too.  But *neither* the prosecution\\nnor the defense is talking.  So one cannot conclude either way due to\\nthe silence of the principals.  \\n\\n\\nOK.  It certainly seemed to me that there was excessive force involved.\\nAnd frankly, the original \"not guilty\" verdict baffled me too.  But then\\nI learned that the prosecution in the first case did not try to convict\\non a charge of excessive force or simple assault which they probably\\nwould have won, they tried to get a conviction on a charge of aggravated\\nassault with intent to inflict serious bodily harm.  A charge, which\\nnews commentators said, was akin to attempted murder under California\\nlaw.  Based on what the prosecution was asking for, it\\'s evident that \\nthe first jury decided that the officers were \"not guilty\".  Note, \\nnot \"not guilty\" of doing wrong, but \"not guilty\" of aggravated assault \\nwith the *intent* of inflicting serious bodily harm.  The seeds of the \\nprosecutions defeat were in their own overconfidence in obtaining a \\nverdict such that they went for the most extreme charge they could.\\n\\nIf the facts as the news commentators presented them are true, then\\nI feel the \"not guilty\" verdict was a reasonable one.\\n\\n\\nThanks mathew, I like the quote.  Pretty funny actually.  (I\\'m a \\nMonty Python fan, you know.  Kind of seems in that vein.)\\n\\nOf course, oversimplifying any moral argument can make it seem\\ncontradictory.  But then, you know that already.  \\n\\nRegards,',\n",
       " \"<stuff deleted>\\n\\nYou mean like: seconds, minutes, hours, days, months, years. . .  :-)\\n\\nRemember,  the Fahrenheit temperature scale is also a centigrade scale.  Some\\nrevisionists tell the history something like this:  The coldest point in a\\nparticular Russian winter was marked on the thermometer as was the body\\ntemperature of a volunteer (turns out he was sick, but you can't win 'em all).\\nThen the space in between the marks on the thermometer was then divided into\\nhundredths.\\n\\t\\t\\t\\t\\t\\t\\t\\t:-)\\n\\nFWIW,\\n\\nDoug Page\\n\",\n",
       " \"\\nIt wasn't especially prominent, as I recall.  However, quite possibly it's\\nno longer on display; NASM, like most museums, has much more stuff than it\\ncan display at once, and does rotate the displays occasionally.\",\n",
       " \"DM> Fact or rumor....?  Madalyn Murray O'Hare an atheist who eliminated the\\nDM> use of the bible reading and prayer in public schools 15 years ago is now\\nDM> going to appear before the FCC with a petition to stop the reading of the\\nDM> Gospel on the airways of America.  And she is also campaigning to remove\\nDM> Christmas programs, songs, etc from the public schools.  If it is true\\nDM> then mail to Federal Communications Commission 1919 H Street Washington DC\\nDM> 20054 expressing your opposition to her request.  Reference Petition number\\n\\nDM> 2493.\\n\\nFalse.  This story has been going around for years.  There's not a drop of\\ntruth.  Note that I don't care for O'Hare (O'Hair?) myself, but this\\nis one thing she's not guilty of.\\n\"]"
      ]
     },
     "execution_count": 160,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "newsgroups_train.data[10:20]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 120,
   "metadata": {},
   "outputs": [],
   "source": [
    "W1 = clf.fit_transform(vectors_tfidf)\n",
    "H1 = clf.components_"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 121,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['people don think just like objective say morality',\n",
       " 'graphics thanks files image file program windows know',\n",
       " 'space nasa launch shuttle orbit moon lunar earth',\n",
       " 'ico bobbe tek beauchaine bronx manhattan sank queens',\n",
       " 'god jesus bible believe christian atheism does belief']"
      ]
     },
     "execution_count": 121,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "show_topics(H1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 122,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[<matplotlib.lines.Line2D at 0x7f15cb8ae0f0>]"
      ]
     },
     "execution_count": 122,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "data": {
      "image/png": "iVBORw0KGgoAAAANSUhEUgAAAXcAAAD8CAYAAACMwORRAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAADl0RVh0U29mdHdhcmUAbWF0cGxvdGxpYiB2ZXJzaW9uIDMuMC4yLCBodHRwOi8vbWF0cGxvdGxpYi5vcmcvOIA7rQAAIABJREFUeJzt3XuUFOWdN/DvTwzmrDFvNJDdHG8Yl2yWbBJNJsYkm2zuYi4QcxNzWc2a9U1OOMm+STaLGolBE42JJlExKwrGaBQxRkBAERCVi8AMtwFmGGYYbsMAM8AwA8y1Z37vH1091PRUdT9VXdXVVf39nMOhu7qm+nm6qn711FPPRVQVRESULKdFnQAiIgoegzsRUQIxuBMRJRCDOxFRAjG4ExElEIM7EVECMbgTESUQgzsRUQIxuBMRJdDpUX3xqFGjdMyYMVF9PRFRLK1fv/6wqo7Ot15kwX3MmDGoqqqK6uuJiGJJRPaYrMdqGSKiBGJwJyJKIAZ3IqIEYnAnIkogBnciogRicCciSiAGdyKiBDIK7iIyXkTqRKRBRKa4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MAtmLoBOPXAphnvZ4P4N+tVgmXA2i3bosXA/iMiJxt3Tp+xlpWSgLJk/XZcRG53KrL/HfbtiKVCXiWq5Del0A6j5NE5AwRuQjAWKQfJDoev1b983KkJ5cHhv5eRWP9vjMB1KrqPbaPErUv3fKZtP1Z1Ke3QfxD+gn9DqSfUt8cdXo8pv1tSD9R3wxgWyb9SNfRLQNQb/1/jrVcAEy38roFQIVtW/+B9IOdBgDfjjhfTyJ9G9uHdGnm+iDzBKAC6RNtJ4D7YXW+K4E8PmbloRrpAPBW2/o3W+mtg61FiNvxax0b66y8Pw3gjAjy+K9IVx9UA9hk/ftsAvelWz4TtT/ZQ5WIKIHiVi1DREQGGNyJiBKIwZ2IKIEY3ImIEojBnYgogRjciYgSiMGdiCiBGNyJiBLo/wOjKVH1+iz6DQAAAABJRU5ErkJggg==\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "plt.plot(clf.components_[0])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 99,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "43.71292605795277"
      ]
     },
     "execution_count": 99,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "clf.reconstruction_err_"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### NMF in summary"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Benefits: Fast and easy to use!\n",
    "\n",
    "Downsides: took years of research and expertise to create"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Notes:\n",
    "- For NMF, matrix needs to be at least as tall as it is wide, or we get an error with fit_transform\n",
    "- Can use df_min in CountVectorizer to only look at words that were in at least k of the split texts"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Truncated SVD"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We saved a lot of time when we calculated NMF by only calculating the subset of columns we were interested in. Is there a way to get this benefit with SVD? Yes there is! It's called truncated SVD.  We are just interested in the vectors corresponding to the **largest** singular values."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<img src=\"images/svd_fb.png\" alt=\"\" style=\"width: 80%\"/>\n",
    "\n",
    "(source: [Facebook Research: Fast Randomized SVD](https://research.fb.com/fast-randomized-svd/))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Shortcomings of classical algorithms for decomposition:"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- Matrices are \"stupendously big\"\n",
    "- Data are often **missing or inaccurate**.  Why spend extra computational resources when imprecision of input limits precision of the output?\n",
    "- **Data transfer** now plays a major role in time of algorithms.  Techniques the require fewer passes over the data may be substantially faster, even if they require more flops (flops = floating point operations).\n",
    "- Important to take advantage of **GPUs**.\n",
    "\n",
    "(source: [Halko](https://arxiv.org/abs/0909.4061))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Advantages of randomized algorithms:"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- inherently stable\n",
    "- performance guarantees do not depend on subtle spectral properties\n",
    "- needed matrix-vector products can be done in parallel\n",
    "\n",
    "(source: [Halko](https://arxiv.org/abs/0909.4061))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Timing comparison"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 123,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 1min 28s, sys: 9.3 s, total: 1min 37s\n",
      "Wall time: 4.06 s\n"
     ]
    }
   ],
   "source": [
    "%time u, s, v = np.linalg.svd(vectors, full_matrices=False)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 124,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn import decomposition\n",
    "import fbpca"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 125,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 1min 18s, sys: 1.4 s, total: 1min 19s\n",
      "Wall time: 3.03 s\n"
     ]
    }
   ],
   "source": [
    "%time u, s, v = decomposition.randomized_svd(vectors, 10)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Randomized SVD from Facebook's library fbpca:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 126,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 26 s, sys: 644 ms, total: 26.7 s\n",
      "Wall time: 1.19 s\n"
     ]
    }
   ],
   "source": [
    "%time u, s, v = fbpca.pca(vectors, 10)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "For more on randomized SVD, check out my [PyBay 2017 talk](https://www.youtube.com/watch?v=7i6kBz1kZ-A&list=PLtmWHNX-gukLQlMvtRJ19s7-8MrnRV6h6&index=7).\n",
    "\n",
    "For significantly more on randomized SVD, check out the [Computational Linear Algebra course](https://github.com/fastai/numerical-linear-algebra)."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## End"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
